<?php

namespace App\Admin\Controllers;

use App\Models\InventoryFunc;
use App\Models\Order;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;

use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Form as myForm;

class OrdersController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('销售订单');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('销售订单');
            $content->description('');

            $content->body($this->form());
        });
    }

    public function destroy($id)
    {
        if ($this->form()->destroy($id)) {
            return response()->json([
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ]);
        } else {
            return response()->json([
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ]);
        }
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Order::class, function (Grid $grid) {
            $grid->model()->select(
                'company.name',
                'agent.name as agent_name',
                'operation.name as operation_name',
                'order.*')
            ->leftjoin('company','company.id','=','order.company_id')
            ->leftjoin('admin_users as operation','order.operater_id','=','operation.username')
            ->leftjoin('agent','agent.id','=','order.agent_id')
            ->where('order.company_id',Admin::user()->company_id)
            ->orderBy('order.created_at', 'desc');

            //$grid->id('编号')
            $grid->id('订单编号')->sortable();
            $grid->type('订单类型')->display(function($v){
                return HelpersController::getStateValue('orderType',$v);
            });
            // $grid->order_contract_id('合同订单编号');
            // $grid->original_id('原始单号');
            // $grid->cowhide_id('皮源编号');
            $grid->name('所属公司');
            $grid->agent_name('客户名称');
            $grid->logistics('物流方式')->display(function($v){
                return HelpersController::getStateValue('Logistics',$v);
            });
            $grid->pay_type('支付方式')->display(function($v){
                return HelpersController::getStateValue('payType',$v);
            });
            $grid->pay_money('已付款金额')->display(function($v){return round($v,2);});
            $grid->actual_money('实付金额')->display(function($v){return round($v,2);});
            //$grid->salesman('销售员');
            //$grid->documentary('跟单员');
            $grid->operation_name('操作人');
            $grid->order_state('订单状态')->display(function($v){
                return HelpersController::getStateValue('orderState',$v);
            });
            $grid->review_state("审核状态")->display(function($v){
                return HelpersController::getStateValue('orderReviewState',$v);
            });
            // $grid->reviewer_id('审核状态')->display(function($v){return $v?"<span class='label label-success'>已审核</span>":"<span class='label label-danger'>未审核</span>";});
            //$grid->invoice('是否开发票');
            $grid->disableExport();//禁用导出按钮
            $grid->actions(function ($actions) {
                // append一个操作
                $actions->disableDelete();//禁用编辑
                $actions->disableEdit();
                $actions->prepend('<a href="'.\Route('orders.show',['id'=>$actions->getKey()]).'"><i class="fa fa-eye"></i></a>');
            });

            $grid->disableExport();//禁用导出按钮

            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->where(function ($query) {
                    $query->where('order.id', 'like', "%{$this->input}%");
                }, '订单编号');

                $filter->where(function ($query) {
                    $query->where('agent.name', 'like', "%{$this->input}%");
                }, '客户名称');

                $filter->where(function ($query) {
                    $query->where('operation.name', 'like', "%{$this->input}%");
                }, '操作人');

            });
        });
    }


    public function show($id)
    {
        $model = new Content();
        $data = \DB::table('order')->select('order.*',
                'agent.name as agent_name',
                'admin_users.name as user_name',
                'company.name as company_name',
                'documentary.name as documentary_name',
                'salesman.name as salesman',
                'reviewer.name as reviewer_name')
        ->leftjoin('company','order.company_id','=','company.id')
        ->leftjoin('agent','order.agent_id','=','agent.id')
        ->leftjoin('admin_users','admin_users.username','=','order.operater_id')
        ->leftjoin('admin_users as documentary','documentary.username','=','agent.merchandiser')
        ->leftjoin('admin_users as salesman','salesman.username','=','agent.salesman')
        ->leftjoin('admin_users as reviewer','reviewer.username','=','order.reviewer_id')
        ->where('order.id',$id)->first();
        $detail_data = \DB::table('order_detail')->select(
            'order_detail.*',
            'sku.name as sku_name',
            'batch_grade.name as batch_grade',
            'batch_thick.name as batch_thick',
            'batch_origin.name as batch_origin',
            'batch_colour.name as batch_colour',
            'batch_avg_size.name as batch_avg_size',
            'batch_min_size.name as batch_min_size')
            ->leftjoin('sku','order_detail.sku_id','=','sku.id')
            ->leftjoin('batchattribute as batch_grade','order_detail.grade','=','batch_grade.id')
            ->leftjoin('batchattribute as batch_thick','order_detail.thick','=','batch_thick.id')
            ->leftjoin('batchattribute as batch_origin','order_detail.origin','=','batch_origin.id')
            ->leftjoin('batchattribute as  batch_colour','order_detail.colour','=','batch_colour.id')
            ->leftjoin('batchattribute as batch_avg_size','order_detail.avg_size','=','batch_avg_size.id')
            ->leftjoin('batchattribute as batch_min_size','order_detail.min_size','=','batch_min_size.id')
            ->where('order_detail.order_id',$id)->get();
        $content = '<div style="width:80%;margin:0 auto;background:#fff;padding:10px;"><h4 style="text-align:center;">基本信息</h4><hr>';
        $headers = [];
        $rows = [
            ['订单编号', $data->id,'订单类型', HelpersController::getStateValue('orderType',$data->type)],

            ['客户名称', $data->agent_name,'物流方式', HelpersController::getStateValue('Logistics',$data->logistics)],
            ['所属公司', $data->company_name,'有货先发？', $data->is_send?"是":"否"],
            ['出库时间',$data->send_time]
        ];
        $table_1 = new Table($headers, $rows);
        $content .= $table_1->render();

        $content .= '<h4 style="text-align:center;">系统信息</h4><hr>';

        // table 2
        $headers = [];
        // foreach ($detail_data as $value) {
        //     $value
        // }
        $rows = [
            ['操作人',$data->user_name,'订单状态',HelpersController::getStateValue('orderState',$data->order_state)],
            ['销售',isset($data->salesman)?$data->salesman:'未维护该客户销售','跟单', isset($data->documentary_name)?$data->documentary_name:'未维护该客户跟单' ],
            ['最后操作人',$data->reviewer_name,'最后操作时间',$data->review_time],
            ['生成时间', $data->created_at,'','']

        ];
        $table2 = new Table($headers, $rows);
        $content .= $table2->render();

        $content .= "<h4 style='text-align:center'>sku信息</h4>";
        $headers = ['sku','合同订单编号','原始单号','皮源编号','尺数','张数','单价','等级','厚度','产地','颜色','平均尺寸','最小尺寸'];
        $rows = [];
        foreach($detail_data as $v){
            $row = [$v->sku_name,$v->contract_id,$v->original_id,$v->cowhide_id,$v->size, $v->num,round($v->price,2),$v->batch_grade,$v->batch_thick,$v->batch_origin,$v->batch_colour,$v->batch_avg_size,$v->batch_min_size];
            array_push($rows, $row);
        }
        $table2 = new Table($headers, $rows);
        $content .= $table2->render();

        $content .= "<h4 style='text-align:center'>备注</h4><hr><p style='background:#efefef;padding:8px;'>".(trim($data->remark)?$data->remark:"无")."</p>";

        $content .= '<h4 style="text-align:center;">财务状态</h4><hr>';

        //    tinyInteger('invoice')->nullable()->comment('是否开发票');
        //    decimal('invoice_money',11,4)->nullable()->comment('发票费用');
        // table 1

        // if($data->reviewer_id){
            $headers = [];

            $rows = [
                ['支付方式', HelpersController::getStateValue('payType',$data->pay_type),
                 '支付状态', HelpersController::getStateValue('paymentState',$data->payment_state)],
                ['订单总价',round($data->total_price,2)."元","优惠金额",round($data->total_price - $data->actual_money)."元"],
                ["实付金额", round($data->actual_money,2)."元","已付款金额",round($data->pay_money,2)."元"],
            ];
            $table = new Table($headers, $rows);
            $content .=  $table->render();
        // }else{
            // $content .= '<p style="text-align:center;background:#efefef;padding:8px;">尚未维护</p>';
        // }
        if(Admin::user()->can('order.charge')){
            $content .= '<h4 style="text-align:center;">主管审核</h4><hr>';
            switch($data->review_state){
                case "CREATED":
                    $form = new myForm();
                    $form->action($data->id.'/auditing');
                    $form->method('POST');
                    $form->disablePjax();
                    $form->plus(["l_button"=>"<input name='reject' class='btn btn-danger' type='submit' value='拒绝' />","r_button"=>"<input name='accept' class='btn btn-success' type='submit' value='通过' />"]);
                    $content .= $form->render();
                break;
                case "FINISHED":
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单已完成</p>";
                break;
                case "INACTIVED":
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单已取消</p>";
                break;
                default:
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>已审核</p>";
            }
        }
        if(Admin::user()->can('order.auditing')){

            $content .= '<h4 style="text-align:center;">财务审核</h4><hr>';
            if($data->review_state == "OUT_CHECK" || $data->review_state == "FINANCE_LAST" || $data->review_state == "FINISHED"){
                $content .=<<<EOD
                <p>销项税： $data->rate %</p>
                <table class='table'>
                  <tr>
                    <th>sku</th>
                    <th>总出库尺寸</th>
                    <th>总出库张数</th>
                    <th>单价</th>
                    <th>总价</th>
                  </tr>
EOD;
// 注意 EOD;必须顶格
                $total_price = 0;
                foreach($detail_data as $v){
                    $actual_out = \DB::table('inventory_checking_detail')
                        ->select(\DB::raw('sum(size) as size'),\DB::raw('sum(num) as num'))
                        ->where(['checking_ASN'=>$id,'type'=>1,'sku_id'=>$v->sku_id,'grade'=>$v->grade,'thick'=>$v->thick,'origin'=>$v->origin,'colour'=>$v->colour,'avg_size'=>$v->avg_size,'min_size'=>$v->min_size])
                        ->first();
                    $total_price += $actual_out->size * $v->price;
                    $content.="<tr><td>$v->sku_name</td><td>".round($actual_out->size,2)."</td><td>".round($actual_out->num,2)."</td><td>".round($v->price,2)." 元</td><td>".round($actual_out->size * $v->price,2)." 元</td></tr>";
                }
                $content .="</table><p style='text-align:right'>合计（不含税）: $total_price 元，税费：".round($total_price*$data->rate,2)." 元</p>";
            }
            switch($data->review_state){
                case "CHARGE_CHECK":
                // case "OUT_CHECK":
                    $form = new myForm();
                    $form->__construct(['pay_type'=>$data->pay_type,'payment_state'=>$data->payment_state,'actual_money'=>$data->actual_money,'pay_money'=>$data->pay_money]);
                    $form->action($data->id.'/finance');
                    $form->method('POST');
                    $form->disablePjax();
                    $payType = HelpersController::getStateOptions('payType');
                    array_shift($payType);
                    $form->select('pay_type','支付方式')->options($payType);
                    $form->select('payment_state','支付状态')->options(HelpersController::getStateOptions('paymentState'));
                    $form->currency('actual_money', '优惠后金额')->symbol("￥");
                    $form->currency('pay_money','已支付金额')->symbol('￥');
                    $form->plus(["l_button"=>"<input name='reject' class='btn btn-danger' type='submit' value='拒绝' />","r_button"=>"<input name='accept' class='btn btn-success' type='submit' value='通过' />"]);
                    $content .= $form->render();
                break;
                case "OUT_CHECK":
                //销售单无需二次审核
                case "FINISHED":
                case "FINANCE_LAST":
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单已完成</p>";
                break;
                case "FINANCE_1ST":
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单已审核</p>";
                break;
                case "INACTIVED":
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单已取消</p>";
                break;
                case "CREATED":
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>主管尚未审核</p>";
                break;
                default:
                    $content .="<p style='background:#efefef;padding:8px;text-align:center'>订单状态异常，联系管理员！</p>";
            }
        }
        $items = [
            'header'      => '销售单',
            'description' => 'order',
            'breadcrumb'  => '',
            'content'     => $content."</div>",
        ];

        return view('admin::content', $items)->render();
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        Admin::script('
            $(document).off("change",".sku_id");
            $(document).on("change",".sku_id", function(e){
                var sku_id = $(this).val();
                var that = $(this);
                agent_id= $(".agent_id").val();
                if(!agent_id){
                    $("#myModalLabel").text("警告")
                    $(".modal-body").text("请先维护客户")
                    $("#myModal").modal()
                }
                $.ajax({
                  method: "POST",
                  url: "/orders/ajaxSkuOtherInfos",
                  data: { sku_id: sku_id, agent_id:agent_id }
                }).success(function( msg ) {
                  var pdom = that.parents(".has-many-fakeModel-form");
                    pdom.find(".thick").removeAttr("required");
                    pdom.find(".origin").removeAttr("required");
                    pdom.find(".grade").removeAttr("required");
                    pdom.find(".avg_size").removeAttr("required");
                    pdom.find(".min_size").removeAttr("required");
                    pdom.find(".colour").next(".select2-container").css("border","1px solid #d2d6de").removeAttr("required");
                    pdom.find(".thick").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".origin").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".grade").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".avg_size").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".min_size").next(".select2-container").css("border","1px solid #d2d6de");
                    pdom.find(".colour").next(".select2-container").css("border","1px solid #d2d6de");
                  msg = JSON.parse(msg);
                  if(msg.price){
                    pdom.find(".price").val(msg.price);
                  }else{
                    alert("尚未维护该sku针对该供应商的销售价")

                    pdom.find(".price").val("");
                  }
                  if(msg.attribute){
                    var attr =  msg.attribute.split(",");
                    for(i in attr){
                        pdom.find("."+attr[i]).attr("required","required");
                        pdom.find("."+attr[i]).next(".select2-container").css("border","1px solid red");
                    }
                  }else{
                    alert("尚未维护该sku的批次属性");
                  }
                });
            });
            $(document).off("change",".agent_id");
            $(document).on("change",".agent_id",function(){
                agent_id= $(".agent_id").val();
                $.ajax({
                  method: "POST",
                  url: "/orders/agentInfo",
                  data: { agent_id: agent_id }
                }).success(function( msg ) {
                  msg = JSON.parse(msg);
                  if(msg){
                    $(".rate").val(msg.out_tax);
                    // var currency;
                    // switch(msg.currency){
                    //     case 0:
                    //         currency = "人民币";
                    //     break;
                    //     case 1:
                    //         currency = "美元";
                    //     break;
                    // }
                    // $(".currency").val(currency);
                  }else{
                    $(".rate").val("");
                    // $(".currency").val("");
                  }
                });
            })
        ');
        return Admin::form(Order::class, function (Form $form) {

            // $form->text('id', 'ID');
            // $suppliers = \DB::table('supplier')->where('status',0)->get();
            $suppliers = \DB::table('agent')->pluck('name','id');
            $form->radio('type','订单类型')->options(HelpersController::getStateOptions('orderType'));
            $form->select('agent_id', '客户名称')->options($suppliers);
            $form->rate('rate', '税率');
            $form->select('warehouse_id', '仓库名称')->options(\DB::table('warehouse')->where('company_id',Admin::user()->company_id)->pluck('name','id'));
            $form->datetime('send_time','出库时间');
            $form->datetime('arrive_time','外协入库时间')->help('外协专用属性');
            $form->select('logistics','物流方式')->options(HelpersController::getStateOptions('Logistics'));
            $form->select('pay_type','支付方式')->options(HelpersController::getStateOptions('payType'));
            // $states = [
            //     'on'  => ['value' => "1", 'text' => '是', 'color' => 'success'],
            //     'off' => ['value' => "0", 'text' => '否', 'color' => 'danger'],
            // ];
            $form->switch('is_send','是否有货先发');
            $form->textarea('remark', '备注');
            $form->html('<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
    </div>
  </div>
</div>');
            $form->hasMany('fakeModel', function (Form\NestedForm $form) {

                $skus= \DB::table('sku')->where('status',0)->pluck('name','id');
                $form->select('sku_id','sku')->options($skus);
                $form->text('contract_id','合同订单编号')->help('合同订单编号可以不填写！');
                $form->text('original_id','原始单号')->help('原始单号可以不填写！');
                $form->text('cowhide_id','皮源编号')->help('皮源编号可以不填写！');
                $form->currency('price','单价')->symbol(' ');
                $form->currency('size','尺数')->symbol(' ');
                $form->number('num','张数');
                $form->select('arrive_sku_id','外协入库SKU')->options($skus)->help('外协专用属性');

                $form->select('grade','等级')->options(\DB::table('batchattribute')->where('parent_id','grade')->pluck('name','id'));
                $form->select('thick','厚度')->options(\DB::table('batchattribute')->where('parent_id','thick')->pluck('name','id'));
                $form->select('origin','产地')->options(\DB::table('batchattribute')->where('parent_id','origin')->pluck('name','id'));
                $form->select('colour','颜色')->options(\DB::table('batchattribute')->where('parent_id','colour')->pluck('name','id'));
                $form->select('min_size','最小尺寸')->options(\DB::table('batchattribute')->where('parent_id','min_size')->pluck('name','id'));
                $form->select('avg_size','平均尺寸')->options(\DB::table('batchattribute')->where('parent_id','avg_size')->pluck('name','id'));
            });
        });
    }

    public function ajaxSkuOtherInfos(Request $req){
        $arr = $req->all();
        $sku = \DB::table('sku')->where(['ID'=>$arr['sku_id'],'status'=>0])->first();
        if($sku){
            if(json_decode($sku->batchattribute)){
                $attribute = implode(",",json_decode($sku->batchattribute));
            }else{
                $attribute = implode(",",json_decode(\DB::table('category')->where(['id'=>$sku->category_id,'status'=>0])->value('batchattribute')));
            }
        }
        if($res = json_decode(json_encode(\DB::table('agent_sell_price_bill_detail')->where(['sku_id'=>$arr['sku_id'],'datam_id'=>$arr['agent_id'],'datam_type'=>1])->orderBy('created_at','desc')->first()),true)){
            $res['attribute'] = $attribute;
            return json_encode($res);

        }else{
            if($res = json_decode(json_encode(\DB::table('agent_sell_price_bill_detail')->where(['sku_id'=>$arr['sku_id'],'datam_type'=>0])->first()),true)){
                $res['attribute'] = $attribute;

                return json_encode($res);
            }
        }
        return json_encode(['attribute'=>$attribute]);
    }

    public function agentInfo(Request $req){
        $arr = $req->all();
        return json_encode(\DB::table('agent')->where('id',$arr['agent_id'])->first());
    }

    public function store(Request $req){
        if(!$req['fakeModel']){
            admin_toastr('没有产生sku单据','error');
            return back()->withInput();
        }
        if(!$req['agent_id']){
            admin_toastr('没有维护客户资料','error');
            return back()->withInput();
        }
        if(!$req['warehouse_id']){
            admin_toastr('没有维护仓库信息','error');
            return back()->withInput();
        }
        if(strtotime($req['send_time']) < strtotime(date("Y-m-d")." 00:00:00")){
            admin_toastr('出货时间不得早于今天','error');
            return back()->withInput();
        }
        if(strtotime($req['send_time']) >= strtotime($req['arrive_time']) && $req['type'] == 1){
            admin_toastr('外协入库时间早于出货时间','error');
            return back()->withInput();
        }
        $id = HelpersController::getId('order_id','O');
        $orderDetails = [];
        $total_amount  = 0;
        foreach ($req['fakeModel'] as $orderDetailArr) {
            if(!$orderDetailArr['sku_id']){continue;}
            if($orderDetailArr['price']<=0){
                admin_toastr('价格存在空值','error');
                return back()->withInput();
            }
            if($orderDetailArr['size']<=0){
                admin_toastr('尺数存在空值','error');
                return back()->withInput();
            }
            if($orderDetailArr['num']<=0){
                admin_toastr('张数存在空值','error');
                return back()->withInput();
            }
            if(!$orderDetailArr['arrive_sku_id'] && $req['type'] == 1){
                admin_toastr('外协入库sku存在空值','error');
                return back()->withInput();
            }
            $orderDetail['order_id'] = $id;
            $orderDetail['sku_id'] = $orderDetailArr['sku_id'];
            $orderDetail['arrive_sku_id'] = $orderDetailArr['arrive_sku_id'];
            $orderDetail['price'] = $orderDetailArr['price'];
            $orderDetail['num'] = $orderDetailArr['num'];
            $orderDetail['size'] = $orderDetailArr['size'];
            $orderDetail['grade'] = $orderDetailArr['grade'];
            $orderDetail['thick'] = $orderDetailArr['thick'];
            $orderDetail['origin'] = $orderDetailArr['origin'];
            $orderDetail['colour'] = $orderDetailArr['colour'];
            $orderDetail['min_size'] = $orderDetailArr['min_size'];
            $orderDetail['avg_size'] = $orderDetailArr['avg_size'];
            $orderDetail['created_at'] =  date('Y-m-d H:i:s');
            $total_amount += $orderDetailArr['price']*$orderDetailArr['size'];
            array_push($orderDetails, $orderDetail);
        }
        if(!$orderDetails){
            admin_toastr('没有产生sku单据','error');
            return back()->withInput();
        }
        \DB::beginTransaction();
        \DB::table('order')
            ->insert(
                [
                    'id' => $id,
                    'type'=>$req['type'],
                    'agent_id'=>$req['agent_id'],
                    'total_price'=>$total_amount,
                    'actual_money'=>$total_amount,
                    'is_send'=>($req['is_send']=="on"?1:0),
                    // 'exchange_amount'=>$total_amount*$req['exchange_rate'],
                    // 'exchange_rate'=>$req['exchange_rate'],
                    'tax'=>$total_amount*$req['rate']*0.01,
                    'rate'=>$req['rate'],
                    'logistics'=> $req['logistics'],
                    'pay_type' => $req['pay_type'],
                    'warehouse_id' => $req['warehouse_id'],
                    'send_time' => $req['send_time'],
                    'remark' => $req['remark'],
                    'arrive_time' => $req['arrive_time'],
                    'updated_at' => date('Y-m-d H:i:s'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'company_id' => Admin::user()->company_id,
                    'operater_id' => Admin::user()->username,
                ]
             );
        \DB::table('order_detail')
            ->insert($orderDetails);
        HelpersController::endId('order_id');

        \DB::commit();
        admin_toastr(trans('admin.save_succeeded'));
        $url = route('orders.index');
        return redirect($url);
    }

    public function finance($id){
        $input= \Illuminate\Support\Facades\Input::all();
        // $validator = \Validator::make($input, [
        //     'pay_type' => 'required',
        //     'payment_state'=>'required',
        //     'actual_money'=>'required',
        //     'pay_money'=>'required'
        // ]);
        // // dd((boolean)$validator);

        // if ($validator->fails()) {
        //     return back()->withInput()->withErrors($validator->errors());
        // }
        // dd($input);
        unset($input['_token']);
        $input['reviewer_id'] = Admin::user()->username;
        $input['review_time'] = date('Y-m-d H:i:s');

        $old = \DB::table('order')->where('id',$id)->first();
        // if($old->payment_state == 2 && $old->review_state == "FINANCE_LAST"){
        //     admin_toastr("订单已付全款,如要变更请联系系统管理员");
        //     return back()->withInput();
        // }
        if($old->review_state == "FINANCE_1ST"){
            admin_toastr("订单已审核,如要变更请联系系统管理员");
            return back()->withInput();
        }
        if($old->review_state == "FINISHED" || $old->review_state == "FINANCE_LAST"){
            admin_toastr("订单已完成,如要变更请联系系统管理员");
            return back()->withInput();
        }
        $model = new InventoryFunc('order',$id);
        if(isset($input['accept'])){
            // 审核通过
            $input['review_state'] = "FINANCE_1ST";
            if($old->review_state == "OUT_CHECK"){
                $input['review_state'] = "FINANCE_LAST";
            }

        }elseif(isset($input['reject'])){
            // 审核不通过

            $input['review_state'] = "INACTIVED";
            unset($input['reject']);
            \DB::beginTransaction();
            try {
                \DB::table('order')->where('id',$id)->update($input);
                $model->insertBillsChecking($input);
                \DB::commit();
            }catch (Exception $e) {
                \DB::rollBack();
                admin_toastr("数据库出错，请联系管理员","error");
                return back()->withInput();
            }
            admin_toastr("审核处理成功");
            $url = route('orders.index');
            return redirect($url);

        }else{
            admin_toastr('未知错误，请联系管理员','error');
            return back()->withInput();
        }
        \DB::beginTransaction();
        unset($input['reject']);
        unset($input['accept']);
        try {
            \DB::table('order')->where('id',$id)->update($input);
            if($old->review_state == "CHARGE_CHECK"){
                $model->insertInventoryChecking()->insertBillsChecking($input);
            }
            \DB::commit();
            admin_toastr("审核处理成功");
            $url = route('orders.index');
            return redirect($url);
        } catch (Exception $e) {
            \DB::rollBack();
            admin_toastr("数据库出错，请联系管理员","error");
            return back()->withInput();

        }
    }

    function auditing($id){
        $input = \Illuminate\Support\Facades\Input::all();
        $input['reviewer_id'] = Admin::user()->username;
        $input['review_time'] = date('Y-m-d H:i:s');
        $unNeedFinance = false;
        if(isset($input['accept'])){
            // 审核通过
            $input['review_state'] = "CHARGE_CHECK";
            if(\DB::table('order')->where('order.id',$id)->leftjoin('agent','order.agent_id','=','agent.id')->value('agent.type') == 1){
                $input['review_state'] = "FINANCE_1ST";
                $unNeedFinance = true;
            }
        }elseif(isset($input['reject'])){
            // 审核不通过
            $input['review_state'] = "INACTIVED";

        }else{
            admin_toastr('未知错误，请联系管理员','error');
            return back()->withInput();
        }
        unset($input['accept']);
        unset($input['reject']);
        unset($input['_token']);
        $model = new InventoryFunc('order',$id);
        \DB::beginTransaction();
            try {
                \DB::table('order')->where('id',$id)->update($input);
                if($unNeedFinance){
                    $model->insertInventoryChecking();
                }
                $model->insertBillsChecking($input);
                \DB::commit();
            }catch (Exception $e) {
                \DB::rollBack();
                admin_toastr("数据库出错，请联系管理员","error");
                return back()->withInput();
            }

        admin_toastr('审核处理成功');
        $url = route('orders.index');
        return redirect($url);
    }
}